<template>
    <div class="repair-operate">
        <el-card class="!border-none" shadow="never">
            <div class="flex items-center mb-4">
                <company-select 
                    @select-company="handleSelectCompany"
                    label=""
                    custom-class="w-[200px] mr-4 mt-4"
                />
                <el-upload
                    class="upload-demo mr-4"
                    :auto-upload="false"
                    :show-file-list="false"
                    accept=".xlsx,.xls"
                    @change="handleFileChange"
                >
                    <el-button type="primary" class="h-[32px]">选择文件</el-button>
                </el-upload>
                <el-button :disabled="!(selectedCompany && tableData.length)" type="primary" class="h-[32px]" @click="handleUpload">开始上传</el-button>
            </div>

            <el-table
                ref="tableRef"
                :data="paginatedData"
                border
                style="width: 100%"
                height="500"
            >
                <el-table-column prop="orderId" label="订单ID(B)" />
                <el-table-column prop="amount" label="订单金额(C)" />
                <el-table-column prop="driverName" label="司机姓名(E)" />
                <el-table-column prop="startAddress" label="出发地(M)" />
                <el-table-column prop="endAddress" label="目的地(N)" />
                <el-table-column prop="useTime" label="用车时间(Q)" />
                <el-table-column prop="createTime" label="创建时间(S)" />
                <el-table-column prop="matchTime" label="匹配时间(S)" />
                <el-table-column prop="startTime" label="行程开始(O)" />
                <el-table-column prop="endTime" label="行程结束(P)" />
                <el-table-column prop="payTime" label="支付时间(L)" />
            </el-table>
            <div class="flex justify-end mt-4">
                <el-pagination
                    v-model:current-page="currentPage"
                    v-model:page-size="pageSize"
                    :total="tableData.length"
                    :page-sizes="[10, 20, 50, 100]"
                    layout="total, sizes, prev, pager, next"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </el-card>
    </div>
</template>

<script lang="ts" setup name="repairOperate">
import type { UploadFile } from 'element-plus'
import feedback from '@/utils/feedback'
import * as XLSX from 'xlsx'
import { ref, computed } from 'vue'
import { upload } from '@/api/supervise/repair-order'
import { useRouter } from 'vue-router'
const router = useRouter()

const tableData = ref<any[]>([])


// 添加公司选择相关的状态和处理函数
const selectedCompany = ref('')

const handleSelectCompany = (companyId: string) => {
    selectedCompany.value = companyId
}

// 添加时间格式转换函数
const formatDateTime = (dateStr: any) => {
    if (!dateStr) return ''
    
    try {
        // 首先判断是否已经是时间格式 (yyyy-mm-dd hh:mm:ss 或 yyyy-mm-dd hh:mm)
        if (typeof dateStr === 'string' && 
            (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(dateStr) || 
             /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/.test(dateStr))) {
            return dateStr
        }

        // 处理 Excel 序列号格式
        const serial = Number(dateStr)
        if (!isNaN(serial)) {
            const utc_days = Math.floor(serial - 25569)
            const utc_value = utc_days * 86400
            const date_info = new Date(utc_value * 1000)
            
            const year = date_info.getFullYear()
            const month = String(date_info.getMonth() + 1).padStart(2, '0')
            const day = String(date_info.getDate()).padStart(2, '0')
            
            // 处理时间部分
            const fractional_day = serial - Math.floor(serial) + 0.0000001
            let total_seconds = Math.floor(86400 * fractional_day)
            const hours = String(Math.floor(total_seconds / 3600)).padStart(2, '0')
            total_seconds %= 3600
            const minutes = String(Math.floor(total_seconds / 60)).padStart(2, '0')
            
            return `${year}-${month}-${day} ${hours}:${minutes}`
        }

        // 尝试解析其他格式的日期
        const date = new Date(dateStr)
        if (!isNaN(date.getTime())) {
            const year = date.getFullYear()
            const month = String(date.getMonth() + 1).padStart(2, '0')
            const day = String(date.getDate()).padStart(2, '0')
            const hours = String(date.getHours()).padStart(2, '0')
            const minutes = String(date.getMinutes()).padStart(2, '0')
            return `${year}-${month}-${day} ${hours}:${minutes}`
        }

        return dateStr
    } catch (e) {
        console.error('日期转换错误:', e)
        return ''
    }
}

// 修改文件上传验证
let uploadFile = ref<File | null>(null)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

// 计算分页后的数据
const paginatedData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return tableData.value.slice(start, end)
})

// 处理每页条数变化
const handleSizeChange = (val: number) => {
    pageSize.value = val
    currentPage.value = 1
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
    currentPage.value = val
}

// 修改 handleFileChange 函数，在设置新数据时重置页码
const handleFileChange = (file: UploadFile) => {
    const rawFile = file.raw
    if (!rawFile) {
        return
    }
    uploadFile.value = rawFile

    const reader = new FileReader()
    reader.onload = (e) => {
        try {
            const data = e.target?.result
            console.log(data)
            const workbook = XLSX.read(data, { type: 'array' })
            const firstSheetName = workbook.SheetNames[0]
            const worksheet = workbook.Sheets[firstSheetName]
            
            // 将 Excel 数据转换为 JSON 格式，用于预览
            const jsonData = XLSX.utils.sheet_to_json(worksheet)
            console.log(jsonData)
            // 映射数据到表格需要的格式，并处理时间格式
            tableData.value = jsonData.map((row: any) => ({
                orderId: row['订单ID'] || '',
                amount: row['乘客应收_金额'] || '',
                driverName: row['司机姓名'] || '',
                startAddress: row['出发地点'] || '',
                endAddress: row['目的地点'] || '',
                useTime: formatDateTime(row['行程开始时间']),
                createTime: formatDateTime(row['订单创建时间']),
                matchTime: formatDateTime(row['行程开始时间']),
                startTime: formatDateTime(row['行程开始时间']),
                endTime: formatDateTime(row['行程结束时间']),
                payTime: formatDateTime(row['订单支付时间'])
            }))
            currentPage.value = 1 // 重置页码
        } catch (error) {
            console.error('解析文件失败:', error)
            feedback.msgError('文件解析失败，请检查文件格式是否正确')
            tableData.value = []
        }
    }
    
    reader.readAsArrayBuffer(rawFile)
}

const handleUpload = async () => {
    if (!selectedCompany.value) {
        feedback.msgError('请先选择公司')
        return
    }
    if (!uploadFile.value) {
        feedback.msgError('请先选择文件')
        return
    }

    try {
        // 创建 FormData 对象
        const formData = new FormData()
        formData.append('company_id', selectedCompany.value)
        formData.append('file', uploadFile.value)

        // 调用上传API
        await feedback.confirm('确认上传数据？')
        await upload(formData)
        // feedback.msgSuccess('文件上传成功,请等待后台处理')
        // 跳转到补传列表页面
        router.push('/order/order/repair')
        // 重置状态
        tableData.value = []
        uploadFile.value = null
        selectedCompany.value = ''
    } catch (error) {
        console.error('Upload failed:', error)
    }
}
</script>

<style lang="scss" scoped>
.repair-operate {
    :deep(.el-table) {
        th {
            background-color: var(--el-fill-color-light);
        }
    }
    
    :deep(.upload-demo) {
        .el-upload {
            display: flex;
            align-items: center;
        }
    }
}
</style>